package com.tzstcl.framework.shiro;

import com.tzstcl.framework.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 公司：天筑科技股份有限公司
 * 作者：zgq
 * 日期：2019年08月08日
 * 说明：
 */
@Slf4j
public class ShiroSessionFilter extends FormAuthenticationFilter {
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpRequest = WebUtils.toHttp(request);
        HttpServletResponse httpResponse = WebUtils.toHttp(response);
        if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                return executeLogin(request, response);
            } else {
                return true;
            }
        } else {
            String loginPage = "/admin/loginPage";
            // 判断session里是否有用户信息
            if (ServletUtils.isAjaxRequest(httpRequest)) {
                // 如果是ajax请求响应头会有，x-requested-with
                httpResponse.setHeader("REDIRECT", "REDIRECT");
                log.debug("登录过期拦截： loginPage="+ loginPage);
                httpResponse.setHeader("CONTEXTPATH", loginPage);
                httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
            } else {
                redirectToLogin(request, response);
            }
            return false;
        }
    }

}
